package com.Servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class contractUpload
 */
@WebServlet("/contractUpload")
public class contractUpload extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public contractUpload() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		// 从request当中获取流信息
		// 并且同时从request中获取注册的学生学号
		String realPath = null;
		String filename = null;
		// System.out.println(sid);
		// String sid="1002";
		InputStream fileSource = request.getInputStream();
		//String tempFileName = "/Users/duyifan/Desktop/tempFile";
		String tempFileName = "/usr/local/tempFile";

		// tempFile指向临时文件
		File tempFile = new File(tempFileName);
		// outputStream文件输出流指向这个临时文件
		FileOutputStream outputStream = new FileOutputStream(tempFile);
		byte b[] = new byte[1024];
		int n;
		while ((n = fileSource.read(b)) != -1) {
			outputStream.write(b, 0, n);
			// 获取文件名称
			RandomAccessFile randomFile = new RandomAccessFile(tempFile, "r");
			randomFile.readLine();
			String str = randomFile.readLine();
			int beginIndex = str.lastIndexOf("=") + 2;
			int endIndex = str.lastIndexOf("\"");
			filename = str.substring(beginIndex, endIndex);
			// System.out.println(filename);
			// 重新定位指针到文件头
			randomFile.seek(0);
			long startPosition = 0;
			int i = 1;
			// 获取文件内容开始的位置
			while ((n = randomFile.readByte()) != -1 && i <= 4) {
				if (n == '\n') {
					startPosition = randomFile.getFilePointer();
					i++;
				}
				// startPosition=startPosition-1;
			}
			// startPosition=startPosition-1;
			// 获取文件内容结束的位置
			randomFile.seek(randomFile.length());
			long endPosition = randomFile.getFilePointer();
			int j = 1;
			while (endPosition >= 0 && j <= 2) {
				endPosition--;
				randomFile.seek(endPosition);
				if (randomFile.readByte() == '\n') {
					j++;
				}
			}
			endPosition--;
			// 设置保存上传文件的路径
			// String realPath=request.getServletContext().getRealPath("/")+"images";
			realPath = getServletContext().getRealPath("/") + "excel";
			System.out.println(realPath);
			// String
			// realPath=request.getSession().getServletContext().getRealPath("")+"images";
			File fileupload = new File(realPath);
			if (!fileupload.exists()) {
				fileupload.mkdir();
			}
			File saveFile = new File(realPath, filename);
			RandomAccessFile randomAccessFile = new RandomAccessFile(saveFile, "rw");
			// 从临时文件中读取文件内容（根据起止位置获取）
			randomFile.seek(startPosition);
			while (startPosition < endPosition) {
				randomAccessFile.write(randomFile.readByte());
				startPosition = randomFile.getFilePointer();
			}
			// 关闭输入输出流，删除临时文件
			randomAccessFile.close();
			randomFile.close();
			// tempFile.delete();

		}
		// 关闭输出流，输入流
		outputStream.close();
		fileSource.close();
		// 将照片名写入到数据库中去

		String inputPath = realPath + "/" + filename;
		request.getRequestDispatcher("contractInputDB-1.jsp?path=" + inputPath + "").forward(request, response);
	}

}
